package com.modelclient.baselib.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.style.AbsoluteSizeSpan;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.modelclient.baselib.util.TUtil;
import com.modelclient.baselib.util.ToastUtil;
import com.modelclient.baselib.widget.ProgressDialog;
import java.io.Serializable;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.Unbinder;


/**
 * 作者：Hxm
 * 创建时间：2017/6/7 16:22
 * 功能说明：
 */

public abstract class BaseFragment<T extends BasePresenter> extends Fragment {

    protected Context mContext;
    public View mRootView;
    Unbinder unbinder;
    protected final static String PAGE_SIZE = "20";

    public T mPresenter;
    public ProgressDialog pDialog;
    private boolean isFirst = true;
    private static final String STATE_SAVE_IS_HIDDEN = "STATE_SAVE_IS_HIDDEN";
    public Typeface iconfont;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContext = getActivity();
        if (mRootView == null) {
            mRootView = getRootView(inflater);
        }

//        iconfont = Typeface.createFromAsset(mContext.getAssets(), "fonts/iconfont.ttf");
        mPresenter = TUtil.getT(this, 0);
        if (this instanceof BaseView) mPresenter.setVM(this);

        unbinder = ButterKnife.bind(this, mRootView);
        if (isFirst) {
            pDialog = new ProgressDialog(mContext);
            initOnlyOnce();
            isFirst = false;
        }
        initView(mRootView);
        return mRootView;
    }

    protected void initOnlyOnce() {
    }

    protected abstract View getRootView(LayoutInflater inflater);

    protected void initView(View mRootView) {
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (unbinder != null) {
            unbinder.unbind();
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        if (mPresenter != null) {
            mPresenter.onDestroy();
        }
    }

    public void initEtHint(EditText editText, String hintText, int size){
        // 新建一个可以添加属性的文本对象
        SpannableString ss = new SpannableString(hintText);
        // 新建一个属性对象,设置文字的大小
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(size,true);
        // 附加属性到文本
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 设置hint
        editText.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
    }

    public void hideSoftInput(EditText et) {
        InputMethodManager inputManager = (InputMethodManager) et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(et.getWindowToken(), 0);
    }

    public void showSoftInput(EditText et) {
        et.setFocusable(true);
        et.setFocusableInTouchMode(true);
        et.requestFocus();

        //延迟弹出软键盘
        Timer timer = new Timer();
        timer.schedule(new TimerTask(){
            @Override
            public void run() {
                InputMethodManager inputManager = (InputMethodManager) et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(et, 0);
            }
        }, 300);
    }

    public void showToast(String str) {
        //Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show();
        Toast toast = Toast.makeText(mContext,"", Toast.LENGTH_LONG);
        toast.setText(str);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    protected void startActivitryWithBundle(@NonNull Class clazz, String[][] val) {
        Intent intent = new Intent(mContext, clazz);
        Bundle bundle = new Bundle();
        if (val != null) {
            for (String[] aVal : val) {
                bundle.putString(aVal[0], aVal[1]);
            }
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 参数传递(注：该方法为了方便传参,参数类型有局限性,传递特殊类型时单独构建Intent) author：FuZhi
     **/
    public void goTo(Class<?> goToCls, Object... values) {
        goTo(false, goToCls, values);
    }

    // <editor-fold defaultstate="collapsed" desc="参数传递(注：该方法为了方便传参,参数类型有局限性,传递特殊类型时单独构建Intent)">
    public void goTo(boolean finish, Class<?> goToCls, Object... values) {
        Intent intent = new Intent(getActivity(), goToCls);
        int i = 0;
        for (Object value : values) {
            Class<?> cls = value.getClass();
            String key = String.valueOf(i);
            if (cls == String.class) {
                intent.putExtra(key, (String) value);
            } else if (value instanceof Serializable) {
                intent.putExtra(key, (Serializable) value);
            } else if (cls == int[].class) {
                intent.putExtra(key, (int[]) value);
            } else if (cls == long[].class) {
                intent.putExtra(key, (long[]) value);
            } else if (cls == boolean[].class) {
                intent.putExtra(key, (boolean[]) value);
            } else if (cls == float[].class) {
                intent.putExtra(key, (float[]) value);
            } else if (cls == double[].class) {
                intent.putExtra(key, (double[]) value);
            } else if (cls == char[].class) {
                intent.putExtra(key, (char[]) value);
            } else if (cls == String[].class) {
                intent.putExtra(key, (String[]) value);
            } else if (cls == Bundle.class) {
                intent.putExtra(key, (Bundle) value);
            } else {
                throw new RuntimeException("不支持参数类型: " + cls.getSimpleName());
            }
            i++;
        }
        startActivity(intent);
        if (finish) {
            getActivity().finish();
        }
    }
    // </editor-fold>

    /**
     * 非空判断
     **/
    public static boolean isEmpty(Object... objs) {
        for (Object obj : objs) {
            if (obj == null) {
                return true;
            } else if (obj instanceof String && obj.equals("")) {
                return true;
            }
        }
        return false;
    }

    public static void VISIBLE(View view) {
        if (view != null) {
            view.setVisibility(View.VISIBLE);
        }
    }

    public static void INVISIBLE(View view) {
        if (view != null) {
            view.setVisibility(View.INVISIBLE);
        }
    }

    public static void GONE(View view) {
        if (view != null) {
            view.setVisibility(View.GONE);
        }
    }

    /**
     * 设置状态栏透明且全屏
     *
     * @param activity
     */
    public static void setFullScreenAndTransparent(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //5.x开始需要把颜色设置透明，否则导航栏会呈现系统默认的浅灰色
                Window window = activity.getWindow();
                View decorView = window.getDecorView();
                //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                decorView.setSystemUiVisibility(option);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            } else {
                Window window = activity.getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
                attributes.flags |= flagTranslucentStatus;
                window.setAttributes(attributes);
            }
        }
    }

    /**
     * 显示Toast信息
     **/
    public void T(Object s) {
        ToastUtil.showToast(String.valueOf(s));
    }

    public boolean onBackpressed() {
        List<Fragment> fragments = getChildFragmentManager().getFragments();
        if (null != fragments && !fragments.isEmpty()) {
            for (Fragment fragment : fragments) {
                if (fragment.isResumed() && fragment.getUserVisibleHint() && fragment instanceof BaseFragment) {
                    BaseFragment f = (BaseFragment) fragment;
                    if (f.onBackpressed()) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
